package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.qiniu.util.Json;

import org.apache.xmlbeans.impl.jam.mutable.MElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author zhouwei
 * @date 2020-01-06 20:09
 */
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    @RequestMapping("/check")
    public Result check(HttpServletResponse response, @RequestBody Map map){
        String telephone = (String) map.get("telephone");
        //取出用户输入的验证码
        String validateCode = (String)map.get("validateCode");
        //取出redis的验证码
        String redisCode = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //校验验证码
        if(redisCode!=null&&validateCode!=null&&redisCode.equals(validateCode)){
            //判断是否为会员，不是就注册为会员
            Member member=memberService.findMember(telephone);
            if(member==null){
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.addMember(member);
            }
            //向客户端写入cookie
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            cookie.setMaxAge(60*60*24*30);//保存30天
            cookie.setPath("/");
            response.addCookie(cookie);
            //将用户信息保存到redis,将对象转化为json键值对，再转化为string，才可以存入redis
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);

            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }else{//校验不通过
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

}
